package com.china08.yxyapi.api.comm;

import java.util.ArrayList;
import java.util.List;

import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.MediaType;
import org.springframework.util.Assert;
import org.springframework.web.bind.annotation.CrossOrigin;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RestController;

import com.china08.yxyapi.api.YxyApiBaseController;
import com.china08.yxyapi.entity.db.res.YxyResSubject;
import com.china08.yxyapi.model.YxyApiReqModel;
import com.china08.yxyapi.repository.db.YxyResBookRepository;
import com.china08.yxyapi.repository.db.YxyResSubjectRepository;

import io.swagger.annotations.ApiOperation;

@CrossOrigin
@RestController
public class SubjectController extends YxyApiBaseController {

    @Autowired
    private YxyResSubjectRepository yrsr;

    @Autowired
    private YxyResBookRepository yrbr;

    @ApiOperation(value = "获得学科")
    @RequestMapping(value = "/api_yw/comm/subject", method = RequestMethod.POST, produces = MediaType.APPLICATION_JSON_UTF8_VALUE)
    public List<RespModel> find(@RequestBody ReqModel reqModel) {
        List<RespModel> list = new ArrayList<SubjectController.RespModel>();
        List<String> listSubjectId = yrbr.findSubjectIdByPhaseIdGroupBySubjectId(reqModel.phase);
        if (listSubjectId.size() > 0) {
            List<YxyResSubject> subjects = yrsr.findByIdInOrderByOrderNum(listSubjectId);
            for (YxyResSubject subject : subjects) {
                RespModel model = new RespModel();
                model.id = subject.getId();
                model.name = subject.getName();
                list.add(model);
            }
        }
        return list;
    }

    protected static class RespModel {
        public String id;
        public String name;
    }

    protected static class ReqModel extends YxyApiReqModel {
        public String phase;

        @Override
        public void autoCheck() {
            Assert.notNull(StringUtils.defaultIfBlank(phase, null), "请指定学段");
        }

    }

}
